<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2020/10/15
 * Time: 9:26
 */

namespace app\commi\controller;


use think\Db;
use think\Request;

class Totalscore extends Base
{
    public function index(){
        $match = Db::table('up_match')
            ->where('match_committee_id', session('com_id'))
            ->field('match_id')
            ->find();
        $group = Db::table('up_match_apply_group')
            ->join('up_match_group', 'mg_id = mag_group_id', 'left')
            ->where('mag_match_id', $match['match_id'])
            ->field('mg_id, mg_name')
            ->select();
        if(Request::instance()->isAjax()){
            $mg_id = input('group_id');
            
            $where['md.match_id'] = $match['match_id'];
            $where['md.flag'] = 3;
            
            if(isset($mg_id) && $mg_id != ''){
                $where['md.level_id'] = $mg_id;
            }
            /*else{
                $where['md.level_id'] = $group[0]['mg_id'];
                $mg_id = $group[0]['mg_id'];
            }*/
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::table('up__match_detail md')
                ->where($where)
                ->count();// 获取总条数
            $count2 = Db::table('up__match_detail md')
                ->where($where)
                ->column('md.id');// 获取总条数
            $lists = Db::table('up__match_detail md')
                ->where($where)
                ->order('md.turn asc')
                ->field('md.id, md.match_id')
                ->select();
            if($lists != []){
                $data = $this->getSCore($mg_id, $match['match_id'], $lists);
                if (count($lists) >= 2) {
                    array_pop($lists);
                    $data_last = $this->getSCore($mg_id, $match['match_id'], $lists);
                    foreach ($data as $k => $v) {
                        foreach ($data_last as $kk => $vv) {
                            if ($v['user_id'] == $vv['user_id']) {
                                $data[$k]['float'] = $v['placing'] - $vv['placing'];
                            }
                        }
                    }
                } else {
                    foreach ($data as $k => $v) {
                        $data[$k]['float'] = 0;
                    }
                }
            }else{
                $data = [];
            }
            foreach($data as $kkk => $vvv){
                $data[$kkk]['mc'] = $kkk + 1;
            }
            $str = '';
            if($count2){
                $str = implode($count2,',');
            }
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'count2' => $str, 'data' => $data]);
        }
        $this->assign([
            'group' => $group
        ]);
        return $this->fetch();
    }
    
    /**
     * 成绩明细
     * @return mixed|\think\response\Json
     */
    public function scoreDetail(){
        if(Request::instance()->isAjax()){
            $where['user_id'] = session('match_user_id');
            $where['match_id'] = session('match_match_id');
            $where['level_id'] = session('match_mg_id');
            $where['umd.flag'] = 3;
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::table('up__match_arrive_record umar')
                ->join('up__match_detail umd', 'umd.id = match_detail_id', 'LEFT')
                ->where($where)
                ->count();// 获取总条数
            $lists = Db::table('up__match_arrive_record umar')
                ->join('up__match_detail umd', 'umd.id = match_detail_id', 'LEFT')
                ->where($where)
                ->field('turn, temp_score')
                ->order('turn asc')
                ->select();
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $user_id = input('user_id');
        $match_id = input('match_id');
        $mg_id = input('mg_id');
        if(isset($user_id) && !empty($user_id)){
            session('match_user_id', $user_id);
        }
        if(isset($match_id) && !empty($match_id)){
            session('match_match_id', $match_id);
        }
        if(isset($mg_id) && !empty($mg_id)){
            session('match_mg_id', $mg_id);
        }
        return $this->fetch('totalscore/scoredetail');
    }
    
    public function outExcel(){
        set_time_limit(0);
        $ids = input('ids');
        if(!$ids){
            return json(['code' => 100, 'msg' => '没有需要导出的数据']);
        }
        $lists = Db::table('up__match_detail md')
            ->where('md.id', 'IN', $ids)
            ->where('md.flag', 3)
            ->order('md.turn asc')
            ->field('md.id, md.match_id')
            ->select();
        $match = Db::table('up__match_detail md')
            ->where('md.id', 'IN', $ids)
            ->field('md.match_id, md.level_id')
            ->find();
        if($lists != []){
            $data = $this->getSCore($match['level_id'], $match['match_id'], $lists);
            if (count($lists) >= 2) {
                array_pop($lists);
                $data_last = $this->getSCore($match['level_id'], $match['match_id'], $lists);
                foreach ($data as $k => $v) {
                    foreach ($data_last as $kk => $vv) {
                        if ($v['user_id'] == $vv['user_id']) {
                            $data[$k]['float'] = $v['placing'] - $vv['placing'];
                        }
                    }
                }
            } else {
                foreach ($data as $k => $v) {
                    $data[$k]['float'] = 0;
                }
            }
        }else{
            $data = [];
        }
        foreach($data as $kkk => $vvv){
            $where['user_id'] = session('match_user_id');
            $where['match_id'] = session('match_match_id');
            $where['level_id'] = session('match_mg_id');
            $data[$kkk]['mc'] = $kkk + 1;
            $truns_score = Db::table('up__match_arrive_record umar')
                ->join('up__match_detail umd', 'umd.id = match_detail_id', 'LEFT')
                ->join('up_match um', 'umd.match_id = um.match_id', 'LEFT')
                ->where('user_id', $vvv['user_id'])
                ->where('umd.match_id', $vvv['ma_match_id'])
                ->where('level_id', $vvv['mg_id'])
                ->field('turn, temp_score, match_title')
                ->order('turn asc')
                ->select();
            foreach($truns_score as $tk => $tv){
                $data[$kkk]['num'. $tv['turn']] = $tv['temp_score'];
                $data[$kkk]['match_title'] = $tv['match_title'];
            }
            $data[$kkk]['truns_score'] = $truns_score;
        }
        $cellname = [
            ['mc', '名次', 10, 'LEFT'],
            ['ma_fan_code', '帆号', 15, 'LEFT'],
            ['user_username', '姓名', 20, 'LEFT'],
            ['club_name', '俱乐部/学校', 25, 'LEFT'],
            ['mg_name', '组别', 20, 'LEFT'],
            ['match_title', '赛事', 20, 'LEFT'],
            ['score', '分数', 15, 'LEFT']
        ];
        $truns = $data[0]['truns_score']; // 用于循环确定轮次
        foreach($truns as $ke => $vo){
            $cell = ['num' . $vo['turn'], '第' . $vo['turn'] . '轮', 10, 'LEFT'];
            array_push($cellname, $cell);
        }
        $res = exportExcel('成绩表', 'Mark', $cellname, $data);
        return json($res);
        
    }
    
    /**
     * 比赛成绩计算
     * @param $mg_id  组别id
     * @param $match_id 比赛id
     * @param $all_details 所有比赛轮次
     * @return success
     */
    public function getSCore($mg_id, $match_id, $all_details)
    {
        $temp_score_arr = [];
        //获取要轮次分段信息（即几轮比赛后去掉一个最低成绩）
        $escape_info = Db::table('up_match')->where('match_id', $match_id)->field('match_mark_max_num,match_mark_lunci')->find();
        $all_user    = Db::table('up_match_apply_info')
            ->where('ma_match_id', $match_id)
            ->where('ma_group', $mg_id)
            ->column('ma_user_id');
        //所有用户
        $all_user_temp_score = [];
        //获取所有用户成绩（有的需要去掉最差成绩）
        foreach ($all_details as $k => $v) {
            //获取某轮次比赛成绩
            $temp_score = Db::table('up__match_arrive_record ar ')
                ->where(['match_detail_id' => $v['id']])
                ->column('ar.temp_score,ar.sensor_id,ar.match_detail_id', 'ar.sensor_id');
            array_push($temp_score_arr, $temp_score);
            //如果有设置相关参数
            if ($escape_info['match_mark_lunci'] && $escape_info['match_mark_max_num']) {
                
                if ((($k + 1) % $escape_info['match_mark_lunci']) == 0) {
                    
                    $count    = count($temp_score_arr);
                    $temp_arr = array_slice($temp_score_arr, $count - $escape_info['match_mark_lunci'], $escape_info['match_mark_lunci']);
                    foreach ($all_user as $ko => $vo) {
                        //每个用户比较成绩
                        $user_scor_temp_arr = $temp_arr;
                        for ($i = ($count - $escape_info['match_mark_lunci']); $i < $count; $i++) {
                            for ($j = $i + 1; $j < $count; $j++) {
                                
                                // 比较数组中两个相邻值的大小
                                if ($user_scor_temp_arr[$i]['boat_' . $vo]['temp_score'] > $user_scor_temp_arr[$j]['boat_' . $vo]['temp_score']) {
                                    $tem                                   = $user_scor_temp_arr[$i]['boat_' . $vo]; // 这里临时变量，存贮$i的值
                                    $user_scor_temp_arr[$i]['boat_' . $vo] = $user_scor_temp_arr[$j]['boat_' . $vo]; // 第一次更换位置
                                    $user_scor_temp_arr[$j]['boat_' . $vo] = $tem; // 完成位置互换
                                }
                            }
                        }
                        
                        foreach ($user_scor_temp_arr as $kh => $vh) {
                            if ($kh >= $escape_info['match_mark_max_num']) {
                                foreach ($temp_arr as $kt => $vt) {
                                    if ($vh['boat_' . $vo]['match_detail_id'] == $vt['boat_' . $vo]['match_detail_id']) {
                                        $temp_score_arr[$kt]['boat_' . $vo]['temp_score'] = 0;
                                    }
                                }
                            }
                        }
                    }
                }
                
            }
        }
        //计算累加成绩
        $user_all_grand_total = [];
        $user_grand_total     = [];
        foreach ($all_user as $ke => $ve) {
            $user_grand_total[$ve] = 0;
            foreach ($temp_score_arr as $kz => $vz) {
                $user_grand_total[$ve] += $vz['boat_' . $ve]['temp_score'];
            }
            array_push($user_all_grand_total, ['user_id' => $ve, 'score' => $user_grand_total[$ve]]);
        }
        
        $this->my_sort($user_all_grand_total, $temp_score_arr);
        
        
        $data = [];
        foreach ($user_all_grand_total as $ky => $ve) {
            $record            = Db::table('up_match_apply_info')
                ->alias('ai')
                ->join("up_u_user u", "u.user_id = ai.ma_user_id ", 'LEFT')
                ->join("up_match_group g", "g.mg_id = ai.ma_group ", 'LEFT')
                ->join("up_club c", "c.club_id = u.user_club_id ", 'LEFT')
                ->where(['ai.ma_match_id' => $match_id, 'ai.ma_group' => $mg_id, 'ma_user_id' => $ve['user_id']])
                ->field('u.user_id,u.user_username,u.user_gender,ai.ma_fan_code,
                ai.ma_boat_code,g.mg_name,g.mg_image,c.club_name,c.club_image, g.mg_id, ai.ma_match_id')
                ->find();
            $record['placing'] = $ky + 1;
            $record['score']   = $ve['score'];
            array_push($data, $record);
        }
        return $data;
    }
    
    
    /**
     * 比赛成绩排序
     * @param $arr  用户总成绩数组
     * @param $temp_score_arr 用户每轮比赛成绩数组
     * @return success
     */
    
    public function my_sort(&$arr, $temp_score_arr)
    {
        $end_limit = count($arr) + 2;
        $count     = count($arr);
        for ($i = 0; $i < $count; $i++) {
            for ($j = $i + 1; $j < $count; $j++) {
                //不同分数
                if ($arr[$i]['score'] > $arr[$j]['score']) {
                    $tem     = $arr[$i]; // 这里临时变量，存贮$i的值
                    $arr[$i] = $arr[$j]; // 第一次更换位置
                    $arr[$j] = $tem; // 完成位置互换
                } elseif ($arr[$i]['score'] == $arr[$j]['score']) {
                    //相同分数，比小分
                    //先计算累加成绩
                    $flag = 0;//用于判断是否需要判断最后一轮次比赛成绩
                    for ($s = 1; $s <= $end_limit; $s++) {
                        $temp_first  = 0;
                        $temp_second = 0;
                        foreach ($temp_score_arr as $key => $value) {
                            if ($value['boat_' . $arr[$i]['user_id']]['temp_score'] == $s) {
                                $temp_first++;
                            }
                            if ($value['boat_' . $arr[$j]['user_id']]['temp_score'] == $s) {
                                $temp_second++;
                            }
                        }
                        if ($temp_first < $temp_second) {
                            $tem     = $arr[$i]; // 这里临时变量，存贮$i的值
                            $arr[$i] = $arr[$j]; // 第一次更换位置
                            $arr[$j] = $tem; // 完成位置互换
                            $flag    = 1;
                            break;
                        } elseif ($temp_first == $temp_second) {
                            continue;
                        } else {
                            $flag = 1;
                        }
                        //判断是否需要判断最后一轮次比赛成绩
                        if ($flag == 0) {
                            $temp_first_boat  = $arr[$count - 1]['boat_' . $arr[$i]['user_id']]['temp_score'];
                            $temp_second_boat = $arr[$count - 1]['boat_' . $arr[$j]['user_id']]['temp_score'];
                            if ($temp_first_boat > $temp_second_boat) {
                                $tem     = $arr[$i]; // 这里临时变量，存贮$i的值
                                $arr[$i] = $arr[$j]; // 第一次更换位置
                                $arr[$j] = $tem; // 完成位置互换
                            }
                        }
                    }
                } else {
                    continue;
                }
            }
        }
    }
}